package com.inspector.app.di.upversion

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.commen.aop.SingleClick
import com.example.commen.net.easyHttp.EasyHttpManager
import com.example.commen.utile.CommonUtils
import com.example.commen.view.UpdateDialog
import com.hjq.http.listener.HttpCallback
import com.hjq.toast.Toaster
import com.inspector.app.di.network.api.APPVersionApi
import java.lang.Exception

class VersionModel : ViewModel() {

    private var updateDialog: UpdateDialog.Builder? = null

    val VersionState: LiveData<APPVersionApi.QueryAPPVersionInfo.Data?>
        get() = _VersionState
    private val _VersionState = MutableLiveData<APPVersionApi.QueryAPPVersionInfo.Data?>()

    /**
     * 获取版本信息
     * @param datetime 2023-11-19
     * @param httpListener 网络请求的生命周期动作(等待弹框)
     */
    @SingleClick
    fun isUpgrade(lifecycleOwner: AppCompatActivity) {
        EasyHttpManager.get().post(lifecycleOwner, APPVersionApi(lifecycleOwner), object : HttpCallback<APPVersionApi.QueryAPPVersionInfo>() {
            override fun onSucceed(result: APPVersionApi.QueryAPPVersionInfo) {
                var data = result.data
                if (data != null && data.newVersion != CommonUtils.getVersionName(lifecycleOwner)) {
                    // 升级对话框
                    if (updateDialog != null && updateDialog!!.isShowing()) {
                        updateDialog!!.dismiss()
                    }
                    updateDialog = UpdateDialog.Builder(lifecycleOwner)
                            // 版本名
                            .setVersionName("版本号: ${data.newVersion}")
                            // 是否强制更新
                            .setForceUpdate(data.forceUpdate)
                            // 更新日志
                            .setUpdateLog(data.updateDescription)
                            // 下载 URL
                            .setDownloadUrl(data.apkDownUrl)
                    updateDialog!!.show()
                    _VersionState.value = data
                }else{
                    _VersionState.value = data
                }
            }

            override fun onFail(e: Exception) {
                Toaster.show(e.message)
            }
        })
    }
}